package cn.com.weshare.lock.redislock;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author dujunguang
 * @description: 秒杀
 * @date: 2022/9/18 17:52
 * @version: 1.0.0
 **/
@RestController
public class SeckillRedissonController6 {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Value("${server.port}")
    private String serverPort;

    @Resource
    private RedissonClient redissonClient;

    @GetMapping("/buy6")
    public String buy6() {
        // 锁的key值，设置成功就是拿到锁了
        String key = "buyUserRedisson";
        RLock lock = redissonClient.getLock(key);
        lock.lock(1000L, TimeUnit.SECONDS);
        try {
            String result = stringRedisTemplate.opsForValue().get("goods:001");
            int goodsNumber = result == null ? 0 : Integer.parseInt(result);
            if (goodsNumber > 0) {
                int realNumber = goodsNumber - 1;
                stringRedisTemplate.opsForValue().set("goods:001", realNumber + "");
                System.out.println("buy success，surplus：" + realNumber + "件\t" + "port：" + serverPort);
                return "buy success：" + realNumber + "\tport：" + serverPort;
            } else {
                System.out.println("sell out：" + serverPort);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return "sell out port：" + serverPort;
    }



}
